# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

library(optparse)
library(magrittr)
library(viridis)
library(xlsx)
library(tidyverse)
option_list <- list(
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file"),
  make_option("--d", type = 'character', action = "store", default = "", help = "the database direcotry"),
  make_option("--config", default = "config.csv", type = "character", help = "config file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

fileName <- "name_map.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

diffData <- read_csv("../../potential/Markers.csv")

nameMapDf <- read_tsv(fileName)
keggIds <- nameMapDf$KEGG
if (all(is.na(keggIds))) {
  quit(status = 0)
}

parent <- "./Sig_Pathways_ID"
createWhenNoExist(parent)

nameParent <- "./Sig_Pathways_Name"
createWhenNoExist(nameParent)

data <- read_csv("Pathway_Result.csv") %>%
  rename(Metabolite = X1)

head(data)
names <- data$Metabolite

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")
library <- configData["library", "value"]
libs <- unlist(strsplit(library, "-"))

fcData <- read_tsv("fc_color.txt")

print(fcData)

source(opt$base)
load("kegg_enrich.RData")
print("===")
print(length(libs))
for (name in names) {
  if (length(libs) > 1) {
    GeneratePathwayJSON(mSet, name, dataDir = opt$d, data.org = libs[1], parent = parent)
  }else {

    PlotMetpaPath(mSet, name, 10, 8, parent = parent, dataDir = opt$d, fcData = fcData)
    PlotMetpaPathByName(mSet, name, 10, 8, parent = nameParent, dataDir = opt$d, fcData = fcData,diffData = diffData)

  }
}










